<?php
/**
 * --------------------------------------------------
 * Copyright © 2021 成都拉风网络 版权所有
 *
 * 功能描述：非对称加密生成token并可以获取数据
 *
 * 创建标识：Created by ZhongYuChan On 2021/4/1 19:50
 *
 * 修改标识：
 * 修改描述：
 *---------------------------------------------------
 */

namespace App\Common;


use App\Exceptions\AppSocketExceptions;
use Exception;

class Mcrypt
{
    private static $iv = "d3hhcHBUb29sc0JBU0U2NA==";

    private static $cipher = "AES-256-CBC";

    private static $key = "m4b0975fb53e14c6vf1c7f93275618e4b5gb2cd7a6p6cq6c2be23cb784acr13w";

    /**
     * 编码
     * @param $params
     * @return false|string
     */
    static public function encode($params)
    {
        $params = json_encode([
            'random'    => rand(100000, 999999),
            'time'      => time(),
            'out_time'  => time()+(60*60*5),
            'params'    => $params,
        ]);
        return openssl_encrypt($params, self::$cipher, self::$key, 0, base64_decode(self::$iv));
    }

    /**
     * 解码
     * @param $text
     * @return array
     * @throws AppSocketExceptions
     */
    static public function decode($text)
    {
        if(empty($text)){
            throw new AppSocketExceptions("错误的token");
        }
        $text = base64_decode($text);
        try {
            $plaintext = openssl_decrypt($text, self::$cipher, self::$key, 0, base64_decode(self::$iv));
            $params = json_decode($plaintext,true);
            Monolog::getInstance()->debug("param",$params);

            if ( empty($params['data']) ) {
                throw new AppSocketExceptions("参数为空");
            }
            return $params['data'];
        } catch (Exception $e) {
            throw new AppSocketExceptions($e->getMessage());
        }
    }

}
